package com.zhenyi.xiaohuoche.admin.web;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.Kv;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.utils.DateUtils;
import com.utils.PathUtils;
import com.utils.interceptor.TestInterceptor;
import com.xhc.common.model.XhcOrder;
import com.xhc.common.model.XhcUserPresent;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;

public class OrderController extends XHCAdminController {
	/**
	 * 票务订单(userTicket)
	 * 按照年与日至年月日筛选,默认显示当日,微信昵称,购票时段,下单时间,支付金额,支付状态(status:1已支付,-1退款,0未支付)
	 */
	public void tickets() {
		Date start = getStartDate();
		Date end = getEndDate();

		Date inStartDate = getStartDate("inStartDate", true);
		Date inEndDate = getEndDate("inEndDate", true);

		Kv kv = Kv.create();
		kv.set("start", start);
		kv.set("end", end);
		if (inStartDate != null && inStartDate != null) {
			kv.set("inStartDate", inStartDate);
			kv.set("inEndDate", inEndDate);
		}

		SqlPara sqlPara = xhcDb.getSqlPara("XHCAdminUserTickets", kv);
		if ("1".equals(getPara("dl"))) {

			ArrayList<Map<String, Object>> rows = CollUtil.newArrayList();
			List<Record> records = xhcDb.find(sqlPara);
			for (Record record : records) {
				Map<String, Object> row1 = new LinkedHashMap<>();
				row1.put("日期", record.get("addTime"));
				row1.put("订单号", record.get("no"));
				row1.put("场次", record.get("time"));
				row1.put("订单号", record.get("out_trade_no"));
				row1.put("姓名", record.get("name"));
				row1.put("电话", record.get("mobile"));
				row1.put("微信", record.get("nickname"));
				int status = record.getInt("status");
				String statusText = "";
				if (status == -1) {
					statusText = "已退款";
				} else if (status == 0) {
					statusText = "未支付";
				} else if (status == 1) {
					statusText = "已支付";
				}
				row1.put("状态", statusText);
				row1.put("使用状态", record.getInt("isUsed") == 1 ? "已使用" : "未使用");
				row1.put("进场时间", record.getDate("inTime"));
				row1.put("出场时间", record.getDate("outTime"));
				row1.put("停留分钟", record.get("duration"));
				rows.add(row1);
			}

			String path = PathUtils.getFile("logs", "xhc", "统计.xlsx");
			ExcelWriter writer = ExcelUtil.getWriter(path);
			// 一次性写出内容，使用默认样式
			writer.write(rows);
			// 关闭writer，释放内存
			writer.close();
			File file = new File(path);
			renderFile(file);
			return;
		}
		Page<Record> pages = xhcDb.paginate(getPage(), getPageSize(), sqlPara);
		// renderPage(pages);
		setRainbow(pages);
		setJsonItems(pages.getList());
		// setData("data", Ret.by("content", "\"\"`''"));
		setData("data", pages.getList());
		render("/xhc/admin/order/tickets.html");
		// renderJson(pages.getList());
	}

	/**
	 * 小礼品订单(userPresent) 按照年与日至年月日筛选,默认显示当日 微信昵称,标题,购买数量,支付金额,状态,快递单号
	 */
	public void presents() {
		Date start = getStartDate();
		Date end = getEndDate();
		SqlPara sqlPara = xhcDb.getSqlPara("XHCAdminPresentsOrder", start, end);
		Page<Record> pages = xhcDb.paginate(getPage(), getPageSize(), sqlPara);
		// renderPage(pages);
		setRainbow(pages);
		setJsonItems(pages.getList());
		render("/xhc/admin/order/presents.html");
	}

	/**
	 * 订单详情,标题,支付金额,状态,物流信息
	 */
	public void presentInfo() {
		Long id = getParaToLong("id");
		XhcUserPresent userPresent = XhcUserPresent.dao.findById(id);
		renderResult(userPresent);
		render("/xhc/admin/order/presentInfo.html");
	}

	/**
	 * 更新物流信息,快递单号
	 */
	@Before(Tx.class)
	public void updatePresent() {
		Long id = getParaToLong("id");
		String telNumber = getPara("telNumber");
		String userName = getPara("userName");
		String address = getPara("address");
		XhcUserPresent userPresent = XhcUserPresent.dao.findById(id);
		String trackNo = getPara("trackNo");
		userPresent.setTrackNo(trackNo);
		if (StrKit.notBlank(trackNo)) {
			userPresent.setStatus(2);
		}
		userPresent.setAddress(address);
		userPresent.setUserName(userName);
		userPresent.setTelNumber(telNumber);
		renderFlag(userPresent.update());
	}

	/**
	 * 所有订单(orders) 按照年与日至年月日筛选,默认显示当日
	 */
	public void orders() {
		Date start = getStartDate();
		Date end = getEndDate();
		SqlPara sqlPara = xhcDb.getSqlPara("AdminOrders", start, end);
		Page<Record> pages = xhcDb.paginate(getPage(), getPageSize(), sqlPara);
		// renderPage(pages);
		setRainbow(pages);
		setItems(JsonKit.toJson(pages.getList()));
		render("/xhc/admin/order/orders.html");
	}

	/**
	 * 按照年月日至年月日下载所有订单 order
	 */
	public void downloadOrders() {
		Date start = getStartDate();
		Date end = getEndDate();
		String title = "所有订单" + DateUtil.now();
		SqlPara sqlPara = xhcDb.getSqlPara("AdminOrders", start, end);
		List<Record> pages = xhcDb.find(sqlPara);
		String excelTitle = DateUtils.dateFormat(start, DateUtils.YYYYMMDD) + "至"
				+ DateUtils.dateFormat(end, DateUtils.YYYYMMDD) + "所有订单";
		ArrayList<Map<String, Object>> rows = CollUtil.newArrayList();
		for (Record record : pages) {
			int status = record.getInt("status");
			String statusString = "";
			if (status == 1) {
				statusString = "已支付";
			} else if (status == 0) {
				statusString = "未支付";
			} else if (status == -1) {
				statusString = "已退款";
			}
			String attach = record.get("attach");
			String attachString = "";
			if (attach.equals("ticket")) {
				attachString = "票";
			} else if (attach.equals("present")) {
				attachString = "礼品";
			}
			int paid = record.get("paid");
			int paidCount = paid / 100;
			Map<String, Object> item = new LinkedHashMap<>();
			item.put("订单号", record.get("out_trade_no"));
			item.put("支付时间", record.getDate("addTime"));
			item.put("价钱（元）", paidCount);
			item.put("订单类型", attachString);
			item.put("客户名称", record.get("nickName"));
			item.put("支付状态", statusString);
			rows.add(item);
		}

		String path = PathUtils.getFile("xhc", "download", title + ".xlsx");
		ExcelWriter writer = ExcelUtil.getWriter(path);
		writer.merge(5, excelTitle);
		// 一次性写出内容
		writer.write(rows);
		// 关闭writer，释放内存
		writer.close();
		File file = new File(path);
		renderFile(file);
	}

	@Override
	public void info() {
		Long id = getParaToLong("id");
		renderSuccess(piaoHashids.encode(id));
	}

	@Clear
	public void queryOrder() {
		Long orderId = getParaToLong("orderId");
		if (orderId == null) {
			renderFailure("orderId null");
			return;
		}
		System.out.println("orderId " + orderId);
		XhcOrder order = XhcOrder.dao.findById(orderId);
		if (order == null) {
			renderFailure("order null");
			return;
		}
		renderSuccess(order.updateOrderStatus());
	}

	@Clear
	public void updateOrder() {
		Long orderId = getParaToLong("orderId");
		if (orderId == null) {
			renderFailure("orderId null");
			return;
		}
		System.out.println("orderId " + orderId);
		XhcOrder order = XhcOrder.dao.findById(orderId);
		if (order == null) {
			renderFailure("order null");
			return;
		}
		order.updateOrderStatus();
		renderMsg("更新成功 " + order.getTradeState());
	}

	public void redunTicket() {
		Long id = getParaToLong("id");
		if (id == null) {
			renderError(403);
			return;
		}
		orderUtils.refundTicket(this, id);
	}

	public void refundPresent() {
		// Long orderId = getParaToLong("orderId");
		Long id = getParaToLong("id");
		if (id == null) {
			renderError(403);
			return;
		}
		orderUtils.refundPresent(this, id);
	}

	@Before(TestInterceptor.class)
	public void rf() {
		String out_trade_no = getPara("no");
		if (StrKit.isBlank(out_trade_no)) {
			renderFailure();
		}
		String total_fee = getPara("fee");
		if (StrKit.isBlank(out_trade_no)) {
			renderFailure();
		}
		// String total_fee = "1";
		// String refundNo = out_trade_no + "RF";
		Ret result = orderUtils.refund(out_trade_no, total_fee);
		renderSuccess(result.get("refund"));
	}

	public void updateTrackNo() {
		Long id = getParaToLong("id");
		if (id == null) {
			renderFailure();
			return;
		}
		// XhcOrder order = XhcOrder.dao.findById(orderId);
		String trackNo = getPara("trackNo");
		if (StrKit.isBlank(trackNo)) {
			renderFailure();
			return;
		}
		XhcUserPresent userPresent = XhcUserPresent.dao.findById(id);
		if (userPresent == null) {
			renderFailure();
			return;
		}
		userPresent.setTrackNo(trackNo);
		userPresent.update();
		renderSuccess();
		renderReload();
	}
}
